package com.idp.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.idp.common.enums.MessageEnum;
import com.idp.common.error.SystemException;
import com.idp.common.model.PageModel;
import com.idp.demo.dto.GoodsDto;
import com.idp.demo.dto.GoodsSearchDto;
import com.idp.demo.entity.GoodsEntity;
import com.idp.demo.mapper.GoodsMapper;
import com.idp.demo.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品Service实现类
 * @author King
 */
@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private GoodsMapper goodsMapper;

	@Override
	public PageModel<GoodsDto> findByPage(GoodsSearchDto goodsSearchDto) {

		PageModel<GoodsDto> page = new PageModel<GoodsDto>();

		page.setList(goodsMapper.getList(goodsSearchDto));

		return page;
	}

	@Override
	public GoodsDto getById(String id) {

		if(ObjectUtil.isEmpty(id)) {
			throw new SystemException(MessageEnum.PARAM_ERROR);
		}

		GoodsDto goodsDto = goodsMapper.getById(id);

		if(goodsDto == null) {
			throw new SystemException(MessageEnum.DATA_NOT_EXIST);
		}

		return goodsDto;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(GoodsDto goodsDto) {

		GoodsEntity goodsEntity = BeanUtil.toBean(goodsDto, GoodsEntity.class);
		goodsEntity.setStatus("2");

		goodsMapper.insert(goodsEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(GoodsDto goodsDto) {

		GoodsEntity goodsEntity = goodsMapper.selectById(goodsDto.getId());

        if(goodsEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }
		CopyOptions copyOptions = new CopyOptions();
		copyOptions.setIgnoreNullValue(true);
		BeanUtil.copyProperties(goodsDto, goodsEntity, copyOptions);

		goodsMapper.updateById(goodsEntity);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delete(String id) {

		GoodsEntity goodsEntity = goodsMapper.selectById(id);

        if(goodsEntity == null) {
            throw new SystemException(MessageEnum.DATA_NOT_EXIST);
        }

		goodsMapper.deleteById(id);
	}

}
